package android.team.app.network;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.team.app.info.WebserviceConfig;

public class AsyncHttpGet extends AsyncHttpBase {

	public AsyncHttpGet(Context context, AsyncHttpResponseListener listener,
			List<NameValuePair> parameters) {
		super(context, listener, parameters);

	}

	public AsyncHttpGet(Context context, AsyncHttpResponseProcess process,
			List<NameValuePair> parameters) {
		super(context, process, parameters);

	}

	@Override
	protected String request(String url) {

		try {
			HttpParams params = new BasicHttpParams();
			if (parameters != null) {
				Iterator<NameValuePair> iterator = parameters.iterator();
				int i = 0;
				while (iterator.hasNext()) {
					NameValuePair nv = iterator.next();
					params.setParameter(nv.getName(), nv.getValue());
					if (i == 0) {
						url += "?"
								+ URLEncoder.encode(nv.getName() + "="
										+ URLEncoder.encode(nv.getValue()));
					} else {
						url += "&"
								+ URLEncoder.encode(nv.getName() + "="
										+ URLEncoder.encode(nv.getValue()));
					}

					i++;
				}
			}
			HttpConnectionParams.setConnectionTimeout(params,
					WebserviceConfig.NETWORK_TIMEOUT);
			HttpConnectionParams.setSoTimeout(params,
					WebserviceConfig.NETWORK_TIMEOUT);
			
			HttpClient httpClient = createHttpClient(params);
			HttpPost httpPost = new HttpPost(url);
			httpPost.setEntity(new UrlEncodedFormEntity(parameters));
			try {
				response  = httpClient.execute(httpPost);
				statusCode = STATUS_NETWORK_OK;
				
			}catch(java.net.SocketTimeoutException e){
				statusCode = STATUS_NETWORK_TIMEOUT;
			}catch (javax.net.ssl.SSLException e) {
				statusCode = STATUS_NETWORK_EXCEIPTION;
			}catch (org.apache.http.conn.ConnectTimeoutException e) {
				statusCode = STATUS_NETWORK_TIMEOUT;
			}catch (ClientProtocolException e) {
				statusCode = STATUS_NETWORK_ERROR;
			}catch (IOException e) {
				statusCode = STATUS_NETWORK_ERROR;
			}catch (Exception e) {
				statusCode = STATUS_NETWORK_EXCEIPTION;
			}			
		} catch (Exception e) {
			statusCode = STATUS_NETWORK_EXCEIPTION;
		}

		return super.request(url);
	}

}
